package com.cwd.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cwd.pojo.Permission;
import com.cwd.pojo.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @PackageName: com.cwd.service
 * @ClassName: SpringSecurityUserService
 * @Author: CWD
 * @Date: 2020/3/12 21:29
 * @Description:
 */
@Component("springSecurityUserService")
public class SpringSecurityUserService implements UserDetailsService {
    //使用dubbo通过网络远程调用服务提供方
    @Reference
    private UserService userService;
    
    //根据用户名查询用户信息(基本信息，角色，权限)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.cwd.pojo.User user = userService.findByUsername(username);
        if(user == null){
            //用户不存在
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<>();
        //获取到当前用户的角色和权限放入list集合中，是当作创建权限用户的第三个参数
       Set<Role> roles = user.getRoles();   //获取当前用户的角色
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();//获取角色的权限
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //这个User是安全框架内部的    org.springframework.security.core.userdetails.User;，
        User securityUser = new User(username,user.getPassword(),list);    //如果是明文密码，必须用{noop}声明
        return securityUser;
    }
}
